
package com.hellobike.haxing.modules.purchase.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.purchase.dto.TPurchaseOrderDetailExcelDto;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrder;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrderDetail;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderDetailService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProService;
import com.hellobike.haxing.modules.supplier.util.BeanUtils;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 /**
 * @Description: t_purchase_order_detail
 * @Author: haxing-boot
 * @Date:   2020-02-12
 * @Version: V1.0
 */
@RestController
@RequestMapping("/purchase/tPurchaseOrderDetail")
@Slf4j
public class TPurchaseOrderDetailController extends BaseController<TPurchaseOrderDetail, ITPurchaseOrderDetailService> {
	@Autowired
	private ITPurchaseOrderDetailService tPurchaseOrderDetailService;
	 @Autowired
	 private ITPurchaseProService tPurchaseProService;
	/**
	 * 分页列表查询
	 *
	 * @param tPurchaseOrderDetail
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "t_purchase_order_detail-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TPurchaseOrderDetail tPurchaseOrderDetail,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TPurchaseOrderDetail> queryWrapper = QueryGenerator.initQueryWrapper(tPurchaseOrderDetail, req.getParameterMap());
		Page<TPurchaseOrderDetail> page = new Page<TPurchaseOrderDetail>(pageNo, pageSize);
		IPage<TPurchaseOrderDetail> pageList = tPurchaseOrderDetailService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param tPurchaseOrderDetail
	 * @return
	 */
	@AutoLog(value = "t_purchase_order_detail-添加",operateType=2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TPurchaseOrderDetail tPurchaseOrderDetail) {
		tPurchaseOrderDetailService.save(tPurchaseOrderDetail);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tPurchaseOrderDetail
	 * @return
	 */
	@AutoLog(value = "t_purchase_order_detail-编辑",operateType=3)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TPurchaseOrderDetail tPurchaseOrderDetail) {
		tPurchaseOrderDetailService.updateById(tPurchaseOrderDetail);
		return Result.ok("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param json
	  * @return
	  */
	 @AutoLog(value = "printOrderDetail-编辑",operateType=3)
	 @PutMapping(value = "/printOrderDetail")
	 public Result<?> printOrderDetail(@RequestBody JSONObject json) {

		 System.out.print(json.toJSONString());
//		 tPurchaseOrderDetailService.updateById(tPurchaseOrderDetail);
		 return Result.ok("编辑成功!");
	 }


	 /**
	  *  编辑
	  *
	  * @param tPurchaseOrderDetail
	  * @return
	  */
	 @AutoLog(value = "修改供应商",operateType=3)
	 @PutMapping(value = "/editSupplier4NewOrder")
	 public Result<?> editSupplier4NewOrder(@RequestBody TPurchaseOrderDetail tPurchaseOrderDetail) {
		 tPurchaseOrderDetailService.editSupplier4NewOrder(tPurchaseOrderDetail);
		 return Result.ok("编辑成功!");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param json
	  * @return
	  */
	 @PostMapping(value = "/detail")
	 public Result<?> detail(@RequestBody JSONObject json) {
		 String ids = json.getString("headerId");
		 QueryWrapper<TPurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
		 queryWrapper.in("parent_order_code", ids);
		 List<TPurchaseOrderDetail> tPurchaseOrderDetails = tPurchaseOrderDetailService.list(queryWrapper);
		 if(ListUtil.isNullOrEmpty(tPurchaseOrderDetails)) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.ok(tPurchaseOrderDetails);
	 }

	 /**
	  * 通过id查询
	  *
	  * @param json
	  * @return
	  */
	 @PostMapping(value = "/detailById")
	 public Result<?> detailById(@RequestBody JSONObject json) {
		 Long id = json.getLong("headerId");
		 QueryWrapper<TPurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
		 queryWrapper.in("id", id);
		 List<TPurchaseOrderDetail> tPurchaseOrderDetails = tPurchaseOrderDetailService.list(queryWrapper);
		 if(ListUtil.isNullOrEmpty(tPurchaseOrderDetails)) {
			 return Result.error("未找到对应数据");
		 }else{
			 tPurchaseOrderDetails.forEach(
					 item -> {
						 item.setWareHouseIds(item.getWarehouseName());
					 }
			 );
		 }
		 return Result.ok(tPurchaseOrderDetails);
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "t_purchase_order_detail-删除",operateType=4)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		tPurchaseOrderDetailService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "t_purchase_order_detail-批量删除",operateType=4)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tPurchaseOrderDetailService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		TPurchaseOrderDetail tPurchaseOrderDetail = tPurchaseOrderDetailService.getById(id);
		if(tPurchaseOrderDetail==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(tPurchaseOrderDetail);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tPurchaseOrder
    */
    @AutoLog(value = "t_purchase_order_detail-导出excel",operateType=6)
    @RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, TPurchaseOrder tPurchaseOrder) {
		List<TPurchaseOrderDetail> tPurchaseOrderDetails = new ArrayList<>();
		List<TPurchaseOrderDetailExcelDto> tPurchaseOrderDetailExcelDtos = new ArrayList<>();
		String title = "采购单";
		if(tPurchaseOrder.getOrderCode() != null){
			title = title + tPurchaseOrder.getOrderCode();
			QueryWrapper<TPurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("parent_order_code", tPurchaseOrder.getOrderCode());
			tPurchaseOrderDetails = tPurchaseOrderDetailService.list(queryWrapper);
			if(ListUtil.isNotEmpty(tPurchaseOrderDetails)){
				BigDecimal totalAmount = new BigDecimal(0);
				for(TPurchaseOrderDetail tPurchaseOrderDetail : tPurchaseOrderDetails){
					TPurchaseOrderDetailExcelDto target = new TPurchaseOrderDetailExcelDto();
					BigDecimal price = new BigDecimal(0);
					if(tPurchaseOrderDetail.getPurchasePrice() != null && tPurchaseOrderDetail.getPurchasePrice().compareTo(new BigDecimal(0)) == 1 && tPurchaseOrderDetail.getPurchaseVolume() != null) {
						price = tPurchaseOrderDetail.getPurchasePrice().multiply(new BigDecimal(tPurchaseOrderDetail.getPurchaseVolume()));
					}
					totalAmount = totalAmount.add(price);
					BeanUtils.copyProperties(tPurchaseOrderDetail,target);
					tPurchaseOrderDetailExcelDtos.add(target);
				}

				if(ListUtil.isNotEmpty(tPurchaseOrderDetailExcelDtos)) {
					for (TPurchaseOrderDetailExcelDto item : tPurchaseOrderDetailExcelDtos) {
						if(item.getPurchasePrice() != null && item.getPurchasePrice().compareTo(new BigDecimal(0)) == 1 && item.getPurchaseVolume() != null  && totalAmount.compareTo(new BigDecimal(0)) == 1) {
							item.setPurchaseAmountPec(item.getPurchasePrice().multiply(new BigDecimal(item.getPurchaseVolume())).divide(totalAmount, 2).multiply(new BigDecimal(100)).toString() + "%");
						}else{
							item.setPurchaseAmountPec("0%");
						}
					}
				}
			}
		}
		return newExportXls(tPurchaseOrderDetailExcelDtos, title);
	}

	 /**
	  * 导出excel
	  *
	  */
	 protected ModelAndView newExportXls(List<TPurchaseOrderDetailExcelDto> exportList, String title) {
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 if(ListUtil.isNotEmpty(exportList)) {
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 mv.addObject(NormalExcelConstants.FILE_NAME, title);
			 mv.addObject(NormalExcelConstants.CLASS, TPurchaseOrderDetailExcelDto.class);
			 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
			 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 }
		 return mv;
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @AutoLog(value = "t_purchase_order_detail-导入excel",operateType=5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TPurchaseOrderDetail.class);
    }

}
